import WxRequest from './request'
import {getStorage,clearStorage} from './storage'
import {toast,modal} from './extendApi'
import {env} from './env'
// 每个项目不同，为了更好复用，基地址设置在这
const axios = new WxRequest({
  baseURL: env.baseURL,
  timeout: 15000
})
// 不同项目，定义不同拦截器，覆盖默认拦截器
axios.interceptor.request = (config) => {
  const token = getStorage("token")
  if(token) config.header["token"] = token
  return config
}
axios.interceptor.response = async (response) => {
  const {isSuccess,data} = response
  if(!isSuccess){
    toast({
      title: "网络异常请重试",
      icon: "error"
    })
    return Promise.reject(response)
  }
  // 根据业务码提示不同内容
  switch (data.code) {
    case 200:
      return data
    case 208:
      const res = await modal({
        content: "登录失效，请重新登录",
        showCancel: false
      })
      if(res){
        clearStorage()
        wx.navigateTo({url: '/pages/login/login'})
      }
      return Promise.reject(response)
    default:
      toast({
        title: "程序错误，请联系客服或稍后尝试"
      })
      return Promise.reject(response)
  }
}
export default axios